home *** CD-ROM | disk | FTP | other *** search
- program TestPower;
-
- {$APPTYPE CONSOLE}
-
- uses
- SysUtils;
-
- function PowerAndMod(a, e, n : integer) : integer;
- {-calculate a^n mod n}
- var
- Exponent : integer;
- BitCount : integer;
- i : integer;
- begin
- {reverse the bits in e and put them in Exponent}
- Exponent := 0;
- for i := 1 to 32 do begin
- if Odd(e) then
- Exponent := (Exponent shl 1) or 1
- else
- Exponent := (Exponent shl 1);
- e := e shr 1;
- end;
- {pop off the clear bits until we reach the first set bit; this will
- be the most significant bit of the original exponent}
- BitCount := 32;
- while not Odd(Exponent) do begin
- Exponent := Exponent shr 1;
- dec(BitCount);
- end;
- {OK, we're ready for the loop}
- Result := 1;
- {for all the bits in the original exponent...}
- for i := pred(BitCount) downto 0 do begin
- {sqaure the intermediate result}
- Result := (Result * Result) mod n;
- {if the current bit is set, multiply by a}
- if Odd(Exponent) then
- Result := (Result * a) mod n;
- Exponent := Exponent shr 1;
- end;
- end;
-
- begin
- writeln(PowerAndMod(3, 3, 437));
- writeln(PowerAndMod(53, 17, 437));
- writeln(PowerAndMod(318, 233, 437));
-
- readln;
- end.
-